#include "dialog.h"
#include "./ui_dialog.h"

#include "QFileDialog"
#include "QRandomGenerator"

Dialog::Dialog(QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::Dialog)
{
    ui->setupUi(this);

    connect(ui->import_button, &QPushButton::clicked, this, &Dialog::import_button_clicked);
    connect(ui->random_button, &QPushButton::clicked, this, &Dialog::random_button_clicked);
}

void Dialog::import_button_clicked()
{
    auto names_file = QFileDialog::getOpenFileName(this, tr("Open Names File"), "", tr("Text Files (*.txt)"));

    QFile file(names_file);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
        return;

    ui->path_label->setText(names_file);
    names.clear();

    QTextStream in(&file);
    while (!in.atEnd()) {
        QString name = in.readLine();
        names.append(name);
    }
}

void Dialog::random_button_clicked()
{
    if (names.length() > 0) {
        quint32 index = QRandomGenerator::global()->bounded(names.length());
        ui->name_label->setText(names.at(index));
    }
}

Dialog::~Dialog()
{
    delete ui;
}
